from django.shortcuts import render
from django.views import View
from apps.areas.models import Area
from django.http import JsonResponse, HttpResponseBadRequest
# Create your views here.


# 查询省级
class AreasCleckView(View):
    def get(self, request):
        # 查询省级数据
        sheng_datas = Area.objects.filter(parent__isnull=True)

        # 生成数据
        sheng_list = []

        for sheng in sheng_datas:
            sheng_list.append({
                'id': sheng.id,
                'name': sheng.name
            })

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'province_list': sheng_list})
# ====================================================================

# 查询市县
class AreasCleckShiquView(View):
    def get(self, request, id):
        try:
            # 拿着id 查子集
            one_date = Area.objects.get(id=id)

            two_date = one_date.subs.all()
        except Exception as e:
            return HttpResponseBadRequest('no')

        # 生成数据
        subs = []
        for city in two_date:
            subs.append({'id': city.id,
                         'name': city.name})

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'sub_data': {
                                 'id': one_date.id,
                                 'name': one_date.name,
                                 'subs': subs
                             }})




